import 'package:BeeApp/CarPage/CarAlipayPage.dart';
import 'package:BeeApp/LoginAndRegister/LoginModelPage.dart';
import 'package:BeeApp/MainPage/MainModelPage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class MainTiXianPage extends StatefulWidget {
  MainTiXianPage({Key key}) : super(key: key);

  @override
  _MainTiXianPageState createState() => _MainTiXianPageState();
}

class _MainTiXianPageState extends State<MainTiXianPage> {
  int payType;
  int openStr = 2;
  UserModel userModel;

  String sxStr = "";
  String aliStr = "支付宝";
  String txPirce = "0.00";
  final priceText = TextEditingController();
  @override
  void initState() {
    super.initState();
    payType = 1;
    uploadUsrData();
    uploadSet();
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        print("state :${res.state} \n code:${res.code}");
        print('授权code值' + res.code);
        if (res.code == null) {
          return;
        }
        toAutch(res.code);
      }
    });
  }

  void uploadSet() {
    DioUtils.noTokenPostHttp(
      context,
      "Usercommon/app_config",
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        if (model.code == 1 && model.data != null) {
          if (mounted) {
            setState(() {
              sxStr = getData("AppType") == "1"
                  ? t["data"]["user_service_charge"].toString()
                  : t["data"]["car_user_service_charge"].toString();
            });
          }
        }
      },
    );
  }

  void toAutch(String codeStr) {
    DioUtils.postHttp(
      context,
      "user/third",
      parameters: {
        "token": getData("token"),
        "platform": "wechat",
        "code": codeStr,
      },
      onSuccess: (t) {
        print(t);
        MainModel model = MainModel.fromJson(t);
        showToast(t["msg"]);
        if (model.code == 1) {
          uploadUsrData();
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  void uploadUsrData() {
    DioUtils.postHttp(
      context,
      "Usercommon/user_info",
      parameters: {"token": getData("token")},
      onSuccess: (t) {
        print(t);
        if (t["code"].toString() == "1") {
          if (mounted) {
            setState(() {
              userModel = UserModel.fromJson(t["data"]);
              openStr = userModel.isThird;
              aliStr = "支付宝 账号:" + userModel.alipayAccount;
              txPirce = userModel.money.toString();
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Widget lineView() {
    return Container(
      height: 1,
      width: 900,
      color: Colors.grey[300],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(context, "提现"),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: ListView(
          children: <Widget>[
            lineView(),
            wxPayView(),
            lineView(),
            aliPayView(),
            Container(height: 10, width: 900, color: Colors.grey[300]),
            priceView(),
            btnView()
          ],
        ),
      ),
    );
  }

  Widget wxPayView() {
    return InkWell(
      child: Container(
        padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
        child: Row(
          children: [
            Image.asset(
                payType == 1
                    ? "images/TiXianSelectImage.png"
                    : "images/TiXianNoneImage.png",
                height: setHeight(30),
                width: setHeight(30)),
            SizedBox(width: setWidth(20)),
            Image.asset(
              "images/WeiXinPayImage.png",
              height: setHeight(50),
              width: setHeight(50),
            ),
            SizedBox(width: setWidth(14)),
            Expanded(
              child: Text(
                "微信支付",
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: setFontSize(30),
                ),
              ),
            ),
            SizedBox(width: setWidth(20)),
            openStr == 2
                ? Container(
                    color: Colors.red,
                    child: InkWell(
                      child: Container(
                        width: setWidth(120),
                        height: setHeight(50),
                        alignment: Alignment.center,
                        // padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(
                              color: Color(0xFF333333), width: 1), //边框
                        ),
                        child: Text(
                          "授权",
                          style: TextStyle(
                            color: Color(0xFF333333),
                            fontSize: setFontSize(28),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      onTap: () async {
                        print("微信授权");
                        var isInstalled = await fluwx.isWeChatInstalled;
                        if (!isInstalled) {
                          showToast("拉取信息失败，请先安装微信");
                          return;
                        }
                        print("is installed $isInstalled");
                        fluwx.sendWeChatAuth(
                            scope: "snsapi_userinfo",
                            state: "wechat_sdk_demo_test");
                      },
                    ))
                : Container()
          ],
        ),
      ),
      onTap: () {
        setState(() {
          payType = 1;
        });
      },
    );
  }

  Widget aliPayView() {
    return InkWell(
      child: Container(
        padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
        child: Row(
          children: [
            Image.asset(
                payType == 2
                    ? "images/TiXianSelectImage.png"
                    : "images/TiXianNoneImage.png",
                height: setHeight(30),
                width: setHeight(30)),
            SizedBox(width: setWidth(20)),
            Image.asset(
              "images/AliPayImage.png",
              height: setHeight(50),
              width: setHeight(50),
            ),
            SizedBox(width: setWidth(20)),
            Expanded(
              child: Text(
                aliStr,
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: setFontSize(30),
                ),
              ),
            ),
            SizedBox(width: setWidth(20)),
            Container(
                color: Colors.red,
                child: InkWell(
                  child: Container(
                    width: setWidth(120),
                    height: setHeight(50),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border:
                          Border.all(color: Color(0xFF333333), width: 1), //边框
                    ),
                    child: Text(
                      aliStr == "支付宝" ? "绑定" : "修改",
                      style: TextStyle(
                        color: Color(0xFF333333),
                        fontSize: setFontSize(28),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  onTap: () {
                    print("支付宝绑定");
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => CarAlipayPage()),
                    ).then((value) {
                      uploadUsrData();
                    });
                  },
                ))
          ],
        ),
      ),
      onTap: () {
        setState(() {
          payType = 2;
        });
      },
    );
  }

  Widget priceView() {
    return Container(
      padding: EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text(
                    "提现金额",
                    style: TextStyle(
                      color: Color(0xFF999999),
                      fontSize: setFontSize(28),
                    ),
                  ),
                  Text(
                    "(收取$sxStr%手续费)",
                    style: TextStyle(
                      color: Color(0xFF999999),
                      fontSize: setFontSize(24),
                    ),
                  ),
                ],
              ),
              InkWell(
                child: Text("提取全部"),
                onTap: () {
                  priceText.text = userModel.money.toString();
                },
              ),
            ],
          ),
          SizedBox(height: 20),
          Row(
            children: [
              Text(
                "¥",
                style: TextStyle(
                    fontSize: setFontSize(50), color: Color(0xFF333333)),
              ),
              SizedBox(width: 10),
              Expanded(
                  child: TextField(
                controller: priceText,
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                textAlign: TextAlign.start,
                cursorColor: Colors.grey[400], //设置光标
                decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: "请输入提现金额",
                    hintStyle: TextStyle(
                        fontSize: setFontSize(30), color: Color(0xFFAEAEAE))),
                style: TextStyle(
                    fontSize: setFontSize(50),
                    color: Color(0xFF333333),
                    fontWeight: FontWeight.bold),
              )),
            ],
          ),
          lineView(),
          SizedBox(height: 8),
          Text("目前可提现金额$txPirce元"),
        ],
      ),
    );
  }

  Widget btnView() {
    return Container(
      alignment: Alignment.center,
      child: InkWell(
        child: Container(
          // height: 40,
          width: 140,
          alignment: Alignment.center,
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: Colors.orange,
            borderRadius: BorderRadius.all(Radius.circular(30)),
            border: Border.all(color: Colors.black, width: 2), //边框
          ),
          child: Text(
            "提现",
            style: TextStyle(
              color: Color(0xFF222222),
              fontSize: setFontSize(34),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        onTap: () {
          removeFocus(context);

          if (payType == 1 && userModel.isThird == 2) {
            showToast("请先进行授权");
            return;
          }
          if (payType == 2 && userModel.isBindAlipay == 2) {
            showToast("请先绑定支付宝");
            return;
          }
          if (priceText.text.length == 0) {
            showToast("请输入提现金额");
            return;
          }

          if (double.parse(priceText.text) == 0) {
            showToast("请输入提现金额");
            return;
          }

          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // title: Text('确认提现至：'),
                content: Text(
                  payType == 2
                      ? '确认提现至：\n${userModel.realname}(${userModel.alipayAccount})的支付宝账号？'
                      : '确认提现至：\n${userModel.openname}的微信账号？',
                  style: TextStyle(
                    color: Color(0xFF333333),
                    fontSize: setFontSize(32),
                  ),
                ),
                actionsPadding: EdgeInsets.only(bottom: setHeight(40)),
                actions: <Widget>[
                  alertBtnView("取消", 0),
                  alertBtnView("确认", 1),
                  // Container(
                  //   width: 900,
                  //   height: setHeight(100),
                  //   child: Row(
                  //     mainAxisAlignment: MainAxisAlignment.end,
                  //     children: <Widget>[
                  //       alertBtnView("取消", 0),
                  //       alertBtnView("确认", 1),
                  //     ],
                  //   ),
                  // ),
                ],
              );
            },
          );
        },
      ),
    );
  }

  Widget alertBtnView(String string, int index) {
    return InkWell(
      child: Container(
        // height: 40,
        width: setWidth(110),
        alignment: Alignment.center,
        // padding: EdgeInsets.all(10),
        // decoration: BoxDecoration(
        //   color: Colors.orange,
        //   borderRadius: BorderRadius.all(Radius.circular(10)),
        //   border: Border.all(color: Colors.black, width: 2), //边框
        // ),
        child: Text(
          string,
          style: TextStyle(
            // color: Color(0xFF222222),
            color: index == 1 ? maincolor : Colors.blue,
            fontSize: setFontSize(34),
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      onTap: () {
        if (index == 0) {
          Navigator.pop(context);
        } else {
          uploadPrice();
        }
      },
    );
  }

  void uploadPrice() {
    showLoading(context);
    DioUtils.postHttp(
      context,
      "Usercommon/withdrawal",
      parameters: {
        "token": getData("token"),
        "money": priceText.text,
        "type": payType.toString(),
      },
      onSuccess: (t) {
        print(t);
        dismissLoading(context);
        // showToast(t["msg"]);
        Navigator.pop(context);
        showAlertDialog(context);
      },
      onError: (error) {
        dismissLoading(context);
        print(error);
      },
    );
  }

  showAlertDialog(BuildContext context) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("您的提现申请已提交成功，\n审核通过后24小时内转入您的账号。"),
          // content: Text("确定要退出吗?"),
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          actions: [
            FlatButton(
              child: Text(
                "确认",
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }
}
